﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Auction_Intranet.Models;
using AuctionDataLayer;
using Auction_Intranet.Helpers;


namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class StatisticsController : ParentController
    {
        DataRepository m_rep = new DataRepository();
      
        public ActionResult Index(long? ticks)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            var today = DateTime.Now;

            if (user != null)
            {
                DateTime requestedDate;
                if (ticks.HasValue)
                {
                    long ticksDate = ticks.Value;
                    requestedDate = new DateTime(ticksDate);
                }
                else
                {
                    requestedDate = DateTime.Now;
                }
                
                if (requestedDate.Hour > 20)
                {
                    requestedDate = requestedDate.AddDays(1);
                }

                var MostPopularDate = DateTime.Now;
                if (requestedDate.Hour > 20)
                {
                    MostPopularDate = MostPopularDate.AddDays(2);
                }
                else
                {
                    MostPopularDate = MostPopularDate.AddDays(1);
                }

                List<Bid> DayResults = m_rep.GetAllBidsByDate(MostPopularDate).ToList();
             
                var bidTimes = m_rep.GetAvailableBidTimes();

                MostlyBiddedHoursModel statmodel = new MostlyBiddedHoursModel();
                AverageBiddedDayModel statRoomModel = new AverageBiddedDayModel();                
                StatisticModel model = new StatisticModel();

                /**************************************************************************/
                //Calculate average price per time unit per day
                List<DayStatisticModel> averages = new List<DayStatisticModel>();
                //int weekNumber = requestedDate.WeekNumber();
                int delta = DayOfWeek.Monday - requestedDate.DayOfWeek;
                DateTime monday = requestedDate.AddDays(delta);
                //if sunday, start showing from the last monday and not a new week
                if (delta == 1)
                {
                    monday = monday.AddDays(-7);
                }

                int bidTimeCount = bidTimes.Count();                
                
                DateTime tempDate = monday;
                //for all days of the week selected
                for (int i = 0; i < 7; i++)
                {
                    var bids = m_rep.GetAllBidsByDate(tempDate);
                    int sum = 0;
                    foreach (var bid in bids)
                    {
                        int start = bidTimes.Where(x => x.Startime == (bid.StartTime)).Select(x => x.Id).FirstOrDefault();
                        int end = bidTimes.Where(x => x.Endtime == (bid.EndTime)).Select(x => x.Id).FirstOrDefault();
                        int singleBidCount = end - start + 1;                        
                        //bidding amount / number of bidded time units
                        var temp = bid.BiddingAmount / singleBidCount;
                        sum += temp;
                        
                    }                    
                    var count = bids.Count();
                    
                    string[] names = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames;
                    
                    if (count == 0)
                    {
                        DayStatisticModel tempModel = new DayStatisticModel();
                        tempModel.day = tempDate;
                        tempModel.abbreviation = names[(int)tempDate.DayOfWeek];
                        tempModel.avgPerTime = 0;
                        averages.Add(tempModel);
                    }
                    else 
                    {
                        var averageUnitValue = sum / count;                        
                        DayStatisticModel tempModel = new DayStatisticModel();
                        tempModel.day = tempDate;
                        tempModel.abbreviation = names[(int)tempDate.DayOfWeek];
                        tempModel.avgPerTime = averageUnitValue;
                        averages.Add(tempModel);                    
                    }
                    tempDate = monday.AddDays(i+1);
                }
                statRoomModel.roomStatistics = averages;
                statRoomModel.date = monday;
                statRoomModel.week = monday.WeekNumber();
                                
                /****************************************************************************/

                statmodel.date = MostPopularDate;
                //create list of all bids for the date and theirs counts                
                List<HourStatisticModel> stats = new List<HourStatisticModel>();
                //var test = m_rep.GetAllPendingBidsByDate(new DateTime(2012,11,1));
                foreach (var item in bidTimes)
                {
                    HourStatisticModel temp = new HourStatisticModel();
                    temp.time = item.Startime.Hour.ToString() + ":" + item.Startime.ToString("mm");
                    temp.numberOFBids = DayResults.Where(x => x.StartTime <= item.Startime && x.EndTime >= item.Endtime && x.Id == x.AnyRoomId).Count();
                    stats.Add(temp);
                }
                statmodel.timeStatistics = stats;
                
                model.mostlyBiddedHour = statmodel;
                model.averageBiddedDay = statRoomModel;
                model.currentDateResult = requestedDate;
                return View(model);
            }
            return View();
        }

        public ActionResult ChartWeekAJAX(string ticks)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            var today = DateTime.Now;
            if (user != null)
            {
                DateTime requestedDate;
                if (ticks != "" && ticks != null)
                {
                    long ticksDate = Convert.ToInt64(ticks);
                    requestedDate = new DateTime(1970, 01, 01).AddMilliseconds(ticksDate);
                }
                else
                {
                    requestedDate = DateTime.Now;
                }

                //invalid date
                if (requestedDate.Date > today.Date && today.Hour < 20 && requestedDate.AddDays(1).Date != today.AddDays(1).Date)
                {
                    return Json("", JsonRequestBehavior.AllowGet);
                }

                if (today.Hour >= 20 && requestedDate.Date > today.AddDays(1).Date)
                {
                    return Json("", JsonRequestBehavior.AllowGet);
                }

                int delta = DayOfWeek.Monday - requestedDate.DayOfWeek;
                DateTime monday = requestedDate.AddDays(delta);
                //if sunday, start showing from the last monday and not a new week
                if (delta == 1)
                {
                    monday = monday.AddDays(-7);
                }
                var bidTimes = m_rep.GetAvailableBidTimes();
                int bidTimeCount = bidTimes.Count();
                DateTime tempDate = monday;
                List<object> averages = new List<object>();
                //for all days of the week selected
                for (int i = 0; i < 7; i++)
                {
                    var bids = m_rep.GetAllBidsByDate(tempDate);
                    int sum = 0;
                    foreach (var bid in bids)
                    {
                        int start = bidTimes.Where(x => x.Startime == (bid.StartTime)).Select(x => x.Id).FirstOrDefault();
                        int end = bidTimes.Where(x => x.Endtime == (bid.EndTime)).Select(x => x.Id).FirstOrDefault();
                        int singleBidCount = end - start + 1;                        
                        //bidding amount / number of bidded time units
                        var temp = bid.BiddingAmount / singleBidCount;
                        sum += temp;
                        
                    }                    
                    var count = bids.Count();

                    string[] names = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames;

                    if (count == 0)
                    {
                        var tempEntry = new { day = names[(int)tempDate.DayOfWeek] + " " + tempDate.Day.ToString(), avgPerTime = 0, realDay = tempDate.Day, realMonth = tempDate.Month, realYear = tempDate.Year };
                        averages.Add(tempEntry);
                    }
                    else
                    {
                        var averageUnitValue = sum / count;
                        //decimal temp = (decimal)averageUnitValue / bidTimeCount;
                        var tempEntry = new { day = names[(int)tempDate.DayOfWeek] + " " + tempDate.Day.ToString(), avgPerTime = averageUnitValue, realDay = tempDate.Day, realMonth = tempDate.Month, realYear = tempDate.Year };
                        averages.Add(tempEntry);
                    }
                    tempDate = monday.AddDays(i + 1);
                }

                return Json(averages, JsonRequestBehavior.AllowGet);
            }
            return Json("", JsonRequestBehavior.AllowGet);        
        }

        public ActionResult ChartAJAX(string ticks)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            if (user != null)
            {
                DateTime requestedDate;
                if (ticks != "" && ticks != null)
                {
                    long ticksDate = Convert.ToInt64(ticks);
                    requestedDate = new DateTime(1970, 01, 01).AddMilliseconds(ticksDate);
                }
                else
                {
                    requestedDate = DateTime.Now;
                }
                var bidTimes = m_rep.GetAvailableBidTimes();
                //create list of all bids for the date and theirs counts                
                List<object> stats = new List<object>();
                var bids = m_rep.GetAllBidsByDate(requestedDate);
                foreach (var item in bidTimes)
                {
                    //HourStatisticModel temp = new HourStatisticModel();
                    var ttime = item.Startime.Hour.ToString() + ":" + item.Startime.ToString("mm");
                    var tnumberOFBids = bids.Where(x => x.StartTime <= item.Startime && x.EndTime >= item.Endtime && x.Id == x.AnyRoomId).Count();
                    var tempEntry = new { time = ttime.ToString(), numberOFBids = tnumberOFBids.ToString() };
                    stats.Add(tempEntry);
                }
                return Json(stats, JsonRequestBehavior.AllowGet);
            }
            return Json("", JsonRequestBehavior.AllowGet);
        }
    }
}
